﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Training.Library.Interfaces;
using Training.Library.DomainObject.Administration.Catalog;
using System.Data.SqlClient;
using System.Data;
using Training.Library.Enum;
using SIPO.Library.DomainObject.Administration.Catalog;
using System.Data.OleDb;

namespace Training.Library.DataAccess.Administration.Catalog
{
    public partial class CabangRepo : ISearchable<Cabang>
    {
        public List<Cabang> GetList(int pageSize, int currentPage, string sortName, string sortOrder,string parameters)
        {
            List<Cabang> tt = new List<Cabang>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    //StringBuilder sbQuery = new StringBuilder();
                    //sbQuery.AppendFormat(" WITH result_set AS ");
                    //sbQuery.AppendFormat(" ( ");
                    //sbQuery.AppendFormat("    SELECT ");
                    //sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    //sbQuery.AppendFormat("      CabangID, NamaCabang, CreatedDate, CreatedBy, UpdatedDate, UpdatedBy ");
                    //sbQuery.AppendFormat("    FROM ");
                    //sbQuery.AppendFormat("      master.Cabang");
                    //sbQuery.AppendFormat("      {0} ",parameters);
                    //sbQuery.AppendFormat(" ) ");
                    //sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = "SP_Cabang_GridPage";// sbQuery.ToString();
                    cmd.Parameters.Add("@startRow", SqlDbType.Int).Value = startRow;
                    cmd.Parameters.Add("@endRow", SqlDbType.Int).Value = endRow;
                    cmd.Parameters.Add("@sortName", SqlDbType.VarChar).Value = sortName;
                    cmd.Parameters.Add("@sortOrder", SqlDbType.VarChar).Value = sortOrder;
                    cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;

                    cmd.CommandType = CommandType.StoredProcedure;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                Cabang t = new Cabang();
                                t.CabangID = dr[Cabang.Fields.CabangID] == DBNull.Value ? 0 : int.Parse(dr[Cabang.Fields.CabangID].ToString());
                                t.NamaCabang = dr[Cabang.Fields.NamaCabang] == DBNull.Value ? string.Empty : dr[Cabang.Fields.NamaCabang].ToString();
                                t.CreatedDate = dr[Cabang.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Cabang.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[Cabang.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[Cabang.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[Cabang.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Cabang.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[Cabang.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[Cabang.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public object SelectScalar(SQL.Function.Aggregate function, string column, string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                       
                        case SQL.Function.Aggregate.Count:
                            cmd.CommandText = "SP_Cabang_GridPage_CountData";
                            //sbQuery.AppendFormat("SELECT COUNT({0}) FROM master.Cabang {1}", column,parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    //cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@column", SqlDbType.VarChar).Value = column;
                    cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public bool SaveUpload(List<Cabang> list)
        {
            bool result = false;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {

                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {

                    foreach(Cabang data in list)
                    {
                          #region Filter By NamaCabang

                            string query = @"SELECT COUNT(NamaCabang) FROM master.CABANG WHERE NamaCabang=@NamaCabang";
                            SqlCommand cmdCount = new SqlCommand(query, conn);
                            cmdCount.Parameters.Add("@NamaCabang", SqlDbType.VarChar).Value = data.NamaCabang;

                            cmdCount.Transaction = txn;
                            var jumlah = cmdCount.ExecuteScalar();
                            int resultJumlah = jumlah == DBNull.Value ? 0 : int.Parse(jumlah.ToString());
                            cmdCount.Dispose();

                        #endregion

                          #region Insert Data Cabang Jika Tidak Ada
                            if (resultJumlah == 0)
                            {
                                query = "SP_Cabang_Insert";
                                SqlCommand cmd = new SqlCommand(query, conn);
                                cmd.CommandType = CommandType.StoredProcedure;
                                cmd.Parameters.Add("@NamaCabang", SqlDbType.VarChar).Value = (object)data.NamaCabang ?? DBNull.Value;
                                cmd.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = (object)data.CreatedDate ?? DBNull.Value;
                                cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = (object)data.CreatedBy ?? DBNull.Value;
                                cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)data.UpdatedDate ?? DBNull.Value;
                                cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)data.UpdatedBy ?? DBNull.Value;

                                cmd.Transaction = txn;
                                cmd.ExecuteNonQuery();
                                cmd.Dispose();
                            }
                            #endregion
                    }
                  



                    result = true;
                    txn.Commit();

                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }
            }

            return result;
        }



        public void Import_To_Grid(string FilePath, string Extension, string isHDR, string connectionStringExcel)
        {

            string conStr = "";

            switch (Extension)
            {

                case ".xls": //Excel 97-03
                    conStr = connectionStringExcel;
                    break;
                case ".xlsx": //Excel 07
                    conStr = connectionStringExcel;
                    break;

            }

            conStr = String.Format(conStr, FilePath, isHDR);

            OleDbConnection connExcel = new OleDbConnection(conStr);

            OleDbCommand cmdExcel = new OleDbCommand();

            OleDbDataAdapter oda = new OleDbDataAdapter();

            DataTable dt = new DataTable();

            cmdExcel.Connection = connExcel;



            //Get the name of First Sheet

            connExcel.Open();

            DataTable dtExcelSchema;

            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

            connExcel.Close();



            //Read Data from First Sheet

            connExcel.Open();

            cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";

            oda.SelectCommand = cmdExcel;

            oda.Fill(dt);

            connExcel.Close();



            //Bind Data to GridView

            //GridView1.Caption = Path.GetFileName(FilePath);

            //GridView1.DataSource = dt;

            //GridView1.DataBind();

        }

    }
}
